export interface HistoryData {
  bottleNumber: string;
  browseTime: string;
  code: string;
}

export class historyViews {
  private data: HistoryData[];

  constructor() {
    this.data = [];
    this.insertDataFromCache();
  }

  insertData(bottleNumber: string, qrcode: string) {
    const index = this.data.findIndex(item => item.bottleNumber === bottleNumber);
    if (index !== -1) {
      return; //存在则不插入，直接跳过
      //如果data列表中存在该值则先删除该值再插入
      //this.data.splice(index, 1);
    }

    if (this.data.length >= 20) {
      this.data.shift(); // 删除最早的数据
    }

    let dateStr = this.getCurrentFormattedDate();
    this.data.push({ browseTime: dateStr, bottleNumber: bottleNumber, code: qrcode } as HistoryData);
    this.saveDataToCache();
  }

  getCurrentFormattedDate(): string {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hour = String(date.getHours()).padStart(2, "0");
    const minute = String(date.getMinutes()).padStart(2, "0");
    const second = String(date.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }

  getDataList() {
    return this.data;
  }

  private insertDataFromCache() {
    const savedData = localStorage.getItem("history_views");
    if (savedData) {
      this.data = JSON.parse(savedData);
    }
  }

  private saveDataToCache() {
    localStorage.setItem("history_views", JSON.stringify(this.data));
  }
}
